﻿#include "form1.h"
#include "ui_form1.h"

#include "cairo.h"
#include <QDebug>
#include <QPainter>

Form1::Form1(QWidget *parent)
    : QWidget(parent),
      ui(new Ui::Form1)
{
    ui->setupUi(this);
}

Form1::~Form1()
{
    delete ui;
}

void Form1::paintEvent(QPaintEvent *pEvent)
{
    Q_UNUSED(pEvent);

    //创建一张图QImage
    int iW = this->width();
    int iH = this->height();
    QImage image(iW, iH, QImage::Format_ARGB32);
    unsigned char *pData = image.bits();
    int iLineStride = image.bytesPerLine();

    //将此图转换为cairo图
    cairo_surface_t *surface = cairo_image_surface_create_for_data(pData, CAIRO_FORMAT_ARGB32, iW, iH, iLineStride);
    //cairo_surface_set_device_scale(surface, 1, 1);
    qDebug() << "devicePixelRatio " << image.devicePixelRatio();
    cairo_surface_set_device_scale(surface, image.devicePixelRatio(), image.devicePixelRatio());
    cairo_t *cr = cairo_create(surface);

    cairo_move_to(cr, 0, 0);
    cairo_line_to(cr, 100, 100);
    cairo_line_to(cr, 100, 200);

    cairo_rectangle(cr, 220, 120, 200, 100);

    cairo_set_line_width(cr, 1.0);           //设置线宽
    cairo_set_source_rgb(cr, 1.0, 0.0, 1.0); //设置线颜色
    cairo_stroke(cr);

    double x = 100.6, y = 328.0;
    double x1 = 102.4 + 100, y1 = 130.4,
           x2 = 153.6 + 240, y2 = 405.6,
           x3 = 230.4 + 400, y3 = 200;

    cairo_move_to(cr, x, y);
    cairo_curve_to(cr, x1, y1, x2, y2, x3, y3);

    cairo_set_line_width(cr, 2.0);           //设置线宽
    cairo_set_source_rgb(cr, 0.0, 0.0, 1.0); //设置线颜色
    cairo_stroke(cr);

    //销毁并退出Cairo绘图环境
    cairo_destroy(cr);
    cairo_surface_destroy(surface);

    //贴图
    QPainter painter(this);
    painter.drawImage(this->rect(), image);
}
